var express = require('express');
var router = express.Router();
const {
    Category,
    Course
} = require('../../models');
const {
    Op
} = require('sequelize');
const { success, error, notFound, formatPagination } = require('../../utils/response');
const { filterCategoryBody, getPaginationParams } = require('../../utils/filter');
/* GET home page. */
// 获取文章列表
/**
 * @api {get} /admin/categories 获取文章列表
 * @apiName GetArticles
 * @apiGroup Articles
 * @apiVersion 1.0.0
 * @apiDescription 获取文章列表
 * @apiPermission 后台管理员
 * 
 */
router.get('/', async function (req, res, next) {
    try {
        const { currentPage, pageSize, offset } = getPaginationParams(req.query);
        const conditions = {
            include: [
                {
                    model: Course,
                    as: 'courses'
                }
            ],
            order: [
                ['id', 'DESC']
            ],
            limit: pageSize,
            offset
        };
        if (req.query.name) {
            conditions.where = {
                name: {
                    [Op.like]: `%${req.query.name}%`
                }
            };
        }
        const {
            rows,
            count
        } = await Category.findAndCountAll(conditions);
        res.json(success(formatPagination(rows, count, currentPage, pageSize), '查询成功'));
    } catch (err) {
        res.json(error('查询失败'));
    }
});
// 查询文章详情
/**
 * @api {get} /admin/categories/:id 查询文章详情
 * @apiName GetArticleById
 * @apiGroup Articles
 * @apiVersion 1.0.0
 */
router.get('/:id', async function (req, res, next) {
    try {
        const {
            id
        } = req.params;
        const category = await Category.findByPk(id);
        if (!category) {
            return res.status(404).json(notFound('分类'));
        }
        res.json(success(category, '查询成功'));
    } catch (err) {
        res.json(error('查询失败', 500, err.message));
    }
});

// 创建文章
/**
 * @api {post} /admin/categories/save 创建文章
 * @apiName CreateArticle
 * @apiGroup Articles
 * @apiVersion 1.0.0
 */
router.post('/save', async function (req, res, next) {
    try {
        const body = filterCategoryBody(req.body);
        const category = await Category.create(body);
        res.status(201).json(success(category, '创建成功', 201));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('更新失败', 400, errors));
        }
        res.json(error('创建失败'));
    }
});

//删除文章
/**
 * @api {delete} /admin/categories/:id 删除文章
 * @apiName DeleteArticle
 * @apiGroup Articles
 * @apiVersion 1.0.0
 */
router.delete('/:id', async function (req, res, next) {
    try {
        const {
            id
        } = req.params;
        const category = await Category.findByPk(id);
        if (!category) {
            return res.status(404).json(notFound('分类'));
        }
        const count = await Course.count({
            where: {
                categoryId: id
            }
        });
        if (count > 0) {
            throw new Error('该分类下有课程，不能删除');
        }
        await category.destroy();
        res.json(success(null, '删除成功', 200));
    } catch (err) {
        res.json(error('删除失败', 500, err.message));
    }
});

// 更新文章
/**
 * @api {post} /admin/categories/update 更新文章
 * @apiName UpdateArticle
 * @apiGroup Articles
 * @apiVersion 1.0.0
 * 
 */
router.post('/update', async function (req, res, next) {
    try {
        const {
            id
        } = req.body;
        const category = await Category.findByPk(id);
        if (!category) {
            return res.status(404).json(notFound('分类'));
        }
        const updateData = filterCategoryBody(req.body);
        await category.update(updateData);
        res.json(success(category, '更新成功'));
    } catch (err) {
        if (err.name === 'SequelizeValidationError') {
            const errors = err.errors.map(e => e.message);
            return res.status(400).json(error('更新失败', 400, errors));
        }
        res.json(error('更新失败'));
    }
});
module.exports = router;